package com.dminvoicemanager.reports;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.dminvoicemanager.DM_InvoiceMenu;
import com.dminvoicemanager.DM_Reports_Generator;
import com.dminvoicemanager.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class DM_Loading_Report extends Activity {
	private static final String TAG = null;
	private String DBNAME = "dminvoicemanager.db";
	// Stock Loading
	private String TEMP_STOCK_LOADING_SUMMARY = "frepStockLoadingSummary";
	private String STOCK_LOAD_HEAD = "fLoadhed";
	private String STOCK_LOAD_DETAIL = "fLoadDet";
	private String USER_SETTINGS = "usersettings";
	String currentReportName, selectFromDate, selectToDate, selectLocFrom,
			selectLocTo,PrintGrandTot,PrintGrandTotTonage;
	TextView txtHeadingReports,totalSum;
	String currentUserTemp, currentUserPrefix, UserLocCode,Stritem_result_13Val;
	EditText dmreportfromdate, dmreporttodate, dmdisplayrepname,
			dmfromlocation, dmtolocation;
	String fromLocName, fromLocCode, toLocName, toLocCode,Stritem_result_10Val;
	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",item_result_4="0",item_result_5="0";
	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("dd-MM-yyyy");
	Date date, LoadingFromDate, LoadingToDate, LoadingOriDate;
	String DefaultDate = "01-01-1900";
	Double TotalCasesLoading =0.0,TotlPiecesLoading =0.0;
	double totalValueSum = 0,totalValueSumtonage=0;
	DecimalFormat numberFormat = new DecimalFormat("#.000000");
	DecimalFormat numberFormatAmt = new DecimalFormat("#,###,###.00");
	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_Reports_Generator.class);
		myIntent.putExtra("TAGID", "RID/RNAME");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_sales_summary_reportb);
		Bundle bundle = getIntent().getExtras();

		currentReportName = bundle.getString("REPORTNAME");
		selectFromDate = bundle.getString("FROMDATE");
		try {
			date = originalFormat.parse(selectFromDate.replaceAll("[-+/.^:,]",
					" "));
			Log.v(TAG, "Old Format :" + originalFormat.format(date));
			Log.v(TAG, "New Format :" + targetFormat.format(date));
			selectFromDate = targetFormat.format(date);
			LoadingFromDate = (Date) targetFormat.parse(selectFromDate);

		} catch (ParseException ex) {

		}
		selectToDate = bundle.getString("TODATE");
		try {
			date = originalFormat.parse(selectToDate.replaceAll("[-+/.^:,]",
					" "));
			Log.v(TAG, "Old Format :" + originalFormat.format(date));
			Log.v(TAG, "New Format :" + targetFormat.format(date));
			selectToDate = targetFormat.format(date);
			LoadingToDate = (Date) targetFormat.parse(selectToDate);

		} catch (ParseException ex) {

		}

		selectLocFrom = bundle.getString("LOCFROM");
		selectLocTo = bundle.getString("LOCTO");

		String[] FromLocDetails = selectLocFrom.split("/");
		fromLocCode = FromLocDetails[0]; // fromLocCode
		fromLocName = FromLocDetails[1]; // fromLocName

		String[] ToLocDetails = selectLocTo.split("/");
		toLocCode = ToLocDetails[0]; // fromLocCode
		toLocName = ToLocDetails[1]; // fromLocName

		txtHeadingReports = (TextView) findViewById(R.id.txtHeadingReports);
		txtHeadingReports.setText(currentReportName);
		dmreportfromdate = (EditText) findViewById(R.id.dmreportfromdate);
		dmreportfromdate.setText(selectFromDate);
		dmreporttodate = (EditText) findViewById(R.id.dmreporttodate);
		dmreporttodate.setText(selectToDate);

		dmfromlocation = (EditText) findViewById(R.id.dmreportfromlocation);
		dmfromlocation.setText(fromLocName);
		dmtolocation = (EditText) findViewById(R.id.dmreporttolocation);
		dmtolocation.setText(toLocName);

		dmdisplayrepname = (EditText) findViewById(R.id.dmdisplayrepname);
		totalSum  = (TextView) findViewById(R.id.totalSum);

		currentuserTemp();

		DisplayLoadingReport();
	}

	private void DisplayLoadingReport() {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_1", "item_result_2",
				"item_result_3","item_result_4","item_result_5" };

		int[] totrdes = new int[] { R.id.item_name, R.id.record_1,
				R.id.record_2,R.id.record_3,R.id.record_4 };

		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null;

		try {
			/*
			 * String query =
			 * "SELECT ItemCode,LitemName,sum(case when RecordChecked = 99 then CaseQty else 0 end),sum(case when RecordChecked = 99 then PiceQty else 0 end) from fLoadDet Where TxnDate >= '"
			 * + selectFromDate.trim() + "' AND TxnDate <= '" +
			 * selectToDate.trim() + "'group by Itemcode";
			 */
			String query = "SELECT fd.ItemCode,LitemName,TxnDate,LocCode,SeqNo,sum(case when RecordChecked = 88 then CaseQty else 0 end),sum(case when RecordChecked = 88 then PiceQty else 0 end),Amt,(fS.Tonnage * fd.Qty)" +
					" from fLoadDet as fd, FSKU as FS ,fItems as FI Where FI.SKUCode = FS.SKUCode AND FI.ItemCode = fd.Itemcode AND (LocCode = '"
					+ fromLocCode + "' OR LocCode = '"
					+ toLocCode + "') AND Amt>0 group by fd.Itemcode,TxnDate,LocCode,SeqNo,Amt,fS.Tonnage,fd.Qty ";
			// ***Select sum queries need seperately 8 to for the combinations
			// String query = "SELECT * from fLoadDet";
			allrowitemsdes = mydb.rawQuery(query, null);
		} catch (Exception e) {
		}

		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {

					// Select Date
					String LoadingDate = allrowitemsdes.getString(2);
			/*		String ToLoadLocation = allrowitemsdes.getString(3); 
					String ToLoadSeq = allrowitemsdes.getString(4);*/
					
					
					try {
						date = originalFormat.parse(LoadingDate.replaceAll(
								"[-+/.^:,]", " "));
						Log.v(TAG, "Old Format :" + originalFormat.format(date));
						Log.v(TAG, "New Format :" + targetFormat.format(date));
						LoadingDate = targetFormat.format(date);
						LoadingOriDate = (Date) targetFormat.parse(LoadingDate);

					} catch (ParseException ex) {
						LoadingDate = "1900-01-01";
					}
					if ((LoadingOriDate.compareTo(LoadingFromDate) >= 0)
							&& (LoadingOriDate.compareTo(LoadingToDate) <= 0)) {
						
						Log.v(TAG, "Slected Area 1" + LoadingFromDate + "To"
								+ LoadingToDate);
						// LoadingFromDate,LoadingToDate
						
						String rawAmount = allrowitemsdes
								.getString(7);
						double rawAmountVal = Double.parseDouble(rawAmount.replaceAll("[,]", ""));
						totalValueSum = totalValueSum + rawAmountVal;
						Stritem_result_10Val = numberFormatAmt.format(totalValueSum);
						
						String rawtonage = allrowitemsdes
								.getString(8);
						double rawTonageVal = Double.parseDouble(rawtonage.replaceAll("[,]", ""));
						totalValueSumtonage = totalValueSumtonage + rawTonageVal;
						Stritem_result_13Val = numberFormat.format(totalValueSumtonage);
						
						String Stritem_10Val = numberFormatAmt.format(rawAmountVal);
						
						String Stritem_13Val = numberFormat.format(rawTonageVal);
						
						PrintGrandTot = Double
								.toString(totalValueSum);
						Log.v(TAG, "PrintGrandTot Format :" + PrintGrandTot);
						
						PrintGrandTotTonage = Double
								.toString(totalValueSumtonage);
						Log.v(TAG, "PrintGrandTot Format :" + PrintGrandTotTonage);
						
						
						// item Description
						item_result_1 = allrowitemsdes.getString(1);
						// Case Qty
						item_result_2 = allrowitemsdes.getString(5);
						// Pieces Qty
						item_result_3 = allrowitemsdes.getString(6);
						// Amt
						item_result_4 = allrowitemsdes.getString(7);
						// tonage
						item_result_5 = allrowitemsdes.getString(8);

						//TotalCasesLoading =0.0,TotlPiecesLoading
						double currentLoadingCases = Double.parseDouble(item_result_2);
						TotalCasesLoading = TotalCasesLoading +currentLoadingCases;
						
						double currentLoadingPieces = Double.parseDouble(item_result_3);
						TotlPiecesLoading = TotlPiecesLoading +currentLoadingPieces;
						
						HashMap<String, String> maptrdes = new HashMap<String, String>();
						maptrdes.put("item_result_1", item_result_1);
						// print Case Qty sales 22 SA
						maptrdes.put("item_result_2", item_result_2);
						// print Pices Qty sales 22 SA
						maptrdes.put("item_result_3", item_result_3);
						// Amt
						maptrdes.put("item_result_4", Stritem_10Val);
						// tonage
						maptrdes.put("item_result_5", Stritem_13Val);
						// fill in the grid_item layout
						fillMapstrdes.add(maptrdes);
						SimpleAdapter adaptertrdes = new SimpleAdapter(this,
								fillMapstrdes,
								R.layout.dm_sales_summary_reportb_raw,
								fromtrdes, totrdes);
						lvtypedes.setAdapter(adaptertrdes);
					} else {
						Log.v(TAG, "Slected Area 2" + LoadingFromDate + "To"
								+ LoadingToDate);
					}

				}
				//-----Print Stock Loading Summary--------
				HashMap<String, String> maptrdesem = new HashMap<String, String>();
				maptrdesem.put("item_result_1", "");
				maptrdesem.put("item_result_2", "");
				maptrdesem.put("item_result_3", "");
				maptrdesem.put("item_result_4", "");
				maptrdesem.put("item_result_5", "");
				// fill in the grid_item layout
				fillMapstrdes.add(maptrdesem);
				SimpleAdapter adaptertrdesem = new SimpleAdapter(this,
						fillMapstrdes,
						R.layout.dm_sales_summary_reportb_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdesem);
				
				
				
				HashMap<String, String> maptrdessum = new HashMap<String, String>();
				maptrdessum.put("item_result_1", "Total");
				// print Case Qty sales 22 SA
				String TotalCasesLoadingStr = Double.toString(TotalCasesLoading);
				maptrdessum.put("item_result_2", TotalCasesLoadingStr);
				// print Pices Qty sales 22 SA
				String TotlPiecesLoadingStr = Double.toString(TotlPiecesLoading);
				maptrdessum.put("item_result_3", TotlPiecesLoadingStr);
				//amt
				maptrdessum.put("item_result_4", Stritem_result_10Val);
				//tonage
				maptrdessum.put("item_result_5", Stritem_result_13Val);

				// fill in the grid_item layout
				fillMapstrdes.add(maptrdessum);
				SimpleAdapter adaptertrdessum = new SimpleAdapter(this,
						fillMapstrdes,
						R.layout.dm_sales_summary_reportb_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdessum);
				
				
				
			}
			//totalSum.setText(PrintGrandTot);
		}
		allrowitemsdes.close();
		mydb.close();
	}

	private void currentuserTemp() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUserTemp = selectCurrentuserrec.getString(1);
					currentUserPrefix = selectCurrentuserrec.getString(2);
					UserLocCode = selectCurrentuserrec.getString(5);
					dmdisplayrepname.setText(currentUserTemp);
				}
			}
		}
		selectCurrentuserrec.close();
		mydb.close();
	}
	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
}
